import React, {useState, useEffect, useRef} from 'react';
import {
    View,
    StyleSheet,
    Button,
    Text,
    Image,
    ScrollView,
    TextInput,
    TouchableOpacity,
    FlatList,
    Alert,
} from 'react-native';
import {ThemeColor} from '../utils/common';
import {useHeaderHeight} from '@react-navigation/elements';
import {useNavigation, useRoute} from '@react-navigation/native';


import  RNFS from 'react-native-fs';

const initData = [
    {name:'Document',path:RNFS.DocumentDirectoryPath},
    {name:'Download',path:RNFS.DownloadDirectoryPath},
    {name:'Temporary',path:RNFS.TemporaryDirectoryPath},
    // {name:'Library',path:RNFS.LibraryDirectoryPath},
    {name:'External',path:RNFS.ExternalDirectoryPath},
    {name:'ExternalStorage',path:RNFS.ExternalStorageDirectoryPath},
]

const FSDemo = ()=>{

    const headerHeight = useHeaderHeight()
    const navigation = useNavigation()
    const {params} = useRoute()

    const [initPath,setInitPath] = useState(null)
    const [data,setData] = useState([])
    const curDirRef = useRef(null)

    useEffect(()=>{
        console.log(params);
        if(params.path){
            readDir(getFileDirItem(params.path))
        }
        /*
           var path = RNFS.DocumentDirectoryPath + '/test.valut';

           // write the file
          RNFS.exists(path).then(isExist=>{
               if(isExist){

               }else{
                   RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
                       .then((success) => {
                           console.log('FILE WRITTEN!');
                       }).catch((err) => {
                       console.log(err.message);
                   });
               }
           })
   */

    },[])



    const initDir = (item)=>{
        console.log('init DIR:',item);
        setInitPath(item)
        curDirRef.current = null
        RNFS.readDir(item.path).then(dirItems=>{
            console.log(dirItems);
            setData(dirItems)
        })
    }



    const readDir = (item)=>{
        console.log('read:',item);
        if(item.isFile()) {
            console.log('file:',item);
            alert(JSON.stringify(item))
            return
        }
        curDirRef.current = item

        RNFS.readDir(item.path).then(dirItems=>{
            console.log(dirItems);
            setData(dirItems)
        })
    }

    const  onBackPress = ()=>{
        console.log('curDir:',curDirRef.current);
        console.log(initPath);
        if(curDirRef.current){
            let curPath = curDirRef.current.path
            let pathArr = curPath.split('/')
            let tail = pathArr[pathArr.length - 1]
            let newPath = curPath.replace('/' + tail,'')
            console.log('back Path:',newPath);
            if(newPath == initPath.path){
                console.log('enter init');
                initDir(initPath)
            }else{
                let newItem = {... curDirRef.current,path:newPath }
                readDir(newItem)
            }

        }else{
            onResetPress()
        }
    }

    const onResetPress = ()=>{
        setData([])
        setInitPath(null)
        curDirRef.current = null
    }

    const getCurPath = ()=>{
        let path
        if(initPath){
            path = initPath.name
        }
        if(curDirRef.current){
            let curPath = curDirRef.current.path
            path = initPath.name + curPath.replace(initPath.path,'')
        }

        return path
    }


    const onLongPress = (item)=>{
        Alert.alert('提示','删除所选内容？',
            [
                {text:'确定',onPress:()=>{
                    RNFS.unlink(item.path).then(()=>{
                        console.log('delete',item);

                        readDir(getFileDirItem(item.path))
                    })
                    },style:'default'},
                {text:'取消',onPress:()=>{},style:'default'}
            ]
        )
    }

    const getFileDirItem = (filePath)=>{
        let pathArr = filePath.split('/')
        let tail = pathArr[pathArr.length - 1]
        const itemDir = filePath.replace(tail,'')
        return {
            path:itemDir,
            isFile:()=>{return false}
        }
    }

    return (
        <View style={[styles.container,{paddingTop:headerHeight}]}>

            <View style={{paddingHorizontal:10}}>
                <View style={{flexDirection:'row',justifyContent:'space-between'}}>

                    <Text style={{color:'#333',fontSize:15}} onPress={onBackPress}>返回</Text>
                    <Text style={{color:'#333',fontSize:15}} onPress={onResetPress}>重置</Text>

                </View>
                <View style={styles.line}/>
                <Text style={{color:'#333',fontSize:15}}>当前:{getCurPath() }</Text>
                <View style={styles.line}/>
            </View>

            <ScrollView
                contentContainerStyle={{paddingHorizontal:10}}
            >
                {
                    !initPath ? initData.map((item,index)=>{
                        return (
                            <TouchableOpacity
                                key={'key_i'+index}
                                onPress={()=>initDir(item)}
                            >
                                <Text style={styles.item}>{item.name}/</Text>
                                <View style={styles.line}/>
                            </TouchableOpacity>
                        )
                    }):
                        data.map((item,index)=> {
                            return (
                                <TouchableOpacity
                                    key={'key_i' + index}
                                    onPress={() => readDir(item, index)}
                                    onLongPress={()=>{
                                        onLongPress(item)
                                    }}
                                >
                                    <Text style={styles.item}>{item.name }{item.isDirectory() ? '/' : ''}</Text>
                                    <View style={styles.line}/>
                                </TouchableOpacity>
                            )
                        })
                }



            </ScrollView>

        </View>
    )
}

export default FSDemo

const styles = StyleSheet.create({
    container:{
        flex:1, backgroundColor:ThemeColor.theme
    },
    item:{
        color:'#333',fontSize:15,marginTop:3
    },
    input:{
        color:'#333',flex:1,height:80,backgroundColor:'#eee',marginTop: 10,borderRadius:4,
        textAlignVertical:'top',padding:10
    },
    line:{
        height:0.3,backgroundColor: '#eee',width:'100%',marginVertical: 10
    },
    nextBtn:{
        alignSelf:'center',marginTop:30
    }
})
